import axios from "axios";
import { ElNotification } from 'element-plus';
import { useAuthStore } from '@/store/authStore';

// 通用通知函数
const showNotification = (title, message, type) => {
    ElNotification({
        title,
        message,
        type,
    });
};

const api = axios.create({
    baseURL: "/api",
});

// 请求拦截器
api.interceptors.request.use((config) => {
    const authStore = useAuthStore();
    const token = authStore?.token;
    const user_id = authStore?.id;
    const role = authStore?.role;

    if (token) {
        config.headers.Authorization = `Bearer ${token}`;

        // 判断角色是否是老师或者学生，如果是，传递 user_id
        if (role === 'teacher' || role === 'student') {
            config.data.user_id = user_id;
        }
    }

    return config;
}, (error) => {
    return Promise.reject(error);
});

// 响应拦截器
api.interceptors.response.use(
    (response) => response,
    async (error) => {
        const status = error.response?.status;

        if (status === 401) {
            const authStore = useAuthStore();
            authStore.clearAuthData();
            window.location.href = '/Login';
        } else {
            const errorMessage = error.response?.data?.message || '网络请求发生错误，请稍后重试';
            showNotification('失败', errorMessage, 'error');
        }

        return Promise.reject(error);
    }
);

// 通用请求函数
export const request = async (url, method = 'POST', data = {}) => {
    try {
        const response = await api({ url, method, data });

        if (response.data.message) {
            showNotification('成功', response.data.message, 'success');
        }

        return response.data;
    } catch (error) {
        throw error;
    }
};

// 单独的 GET 请求函数
export const requestGet = async (url, params = {}) => {
    try {
        const queryString = new URLSearchParams(params).toString();
        const fullUrl = queryString ? `${url}?${queryString}` : url;
        const response = await api.get(fullUrl);

        return response.data;
    } catch (error) {
        throw error;
    }
};
